# -*- coding: utf-8 -*-
import scrapy
import urllib

class CodingSpider(scrapy.Spider):
    name = 'coding'
    allowed_domains = ['coding.imooc.com']
    start_urls = ['https://coding.imooc.com/']

    def parse(self, response):
        if response.status == 200:
            navs = response.css(".shizhan-header-nav a")
            for nav in navs:
                nav_href = nav.css("::attr(href)").extract_first()
                nav_name = nav.css("::text").extract_first()
                if nav_href != '/':
                    type_url = urllib.parse.urljoin(response.url, nav_href)
                    type_name = nav_name
                    type_code = nav_href
                    yield Request(url=type_url, meta={
                        'pid_code': type_code
                        }, callback=this.parseLevelTwo)

    def parseLevelTwo(self, response):
        if response.status == 200:
            levelTwoNavs = response.css('.shizhan-skill-placeholder a')
            for levelTwoNav in levelTwoNavs:
                nav_href = levelTwoNav.css("::attr(href)").extract_first()
                nav_name = levelTwoNav.css("::text").extract_first()
                if nav_href != '/':
                    type_url = urllib.parse.urljoin(response.url, nav_href)
                    type_name = nav_name
                    type_code = nav_href
                    type_pid_code = response.meta['pid_code']
                    yield Request(url=type_url, meta={
                        'pid_code': type_code
                        }, callback=this.parseCourseLists)

    def parseCourseLists(self, response):
        if response.status == 200:
            courseLists = response.css(".shizhan-course-wrap")
            for courseList in courseLists:
                course_name = courseList.css(".img-box .shizhan-course-img")[0].css('::attr(alt)').extract_first()
                course_img = courseList.css(".img-box .shizhan-course-img")[0].css('::attr(src)').extract_first()
                teacher_name = courseList.css(".img-box .shizhan-course-img")[1].css('::attr(alt)').extract_first()
                teacher_img = courseList.css(".img-box .shizhan-course-img")[1].css('::attr(src)').extract_first()
                course_grade = courseList.css(".grade::text").extract()
                course_sale_num = courseList.css(".shizhan-info span")[1].css("::text").extract_first()
                course_desc = courseList.css(".shizan-desc::text").extract_first()




# response.css(".shizhan-course-wrap")[3].css(".img-box .shizhan-course-img")[0].css('::attr(alt)')
# response.css(".shizhan-course-wrap")[3].css(".img-box .shizhan-course-img")[0].css('::attr(src)')
# response.css(".shizhan-course-wrap")[3].css(".shizhan-info")
# response.css(".shizhan-course-wrap")[3].css(".shizan-desc::text").extract_first()